package com.maimang.platform.crm.controller;

import com.maimang.platform.annotation.Log;
import com.maimang.platform.annotation.PassToken;
import com.maimang.platform.base.BaseController;
import com.maimang.platform.base.Result;
import com.maimang.platform.common.config.RoleKeyConstant;
import com.maimang.platform.common.entity.SysRole;
import com.maimang.platform.common.entity.SysUser;
import com.maimang.platform.common.service.SysDeptService;
import com.maimang.platform.common.service.SysUserService;
import com.maimang.platform.common.utils.DateUtils;
import com.maimang.platform.common.utils.ExcelUtil;
import com.maimang.platform.common.utils.ShiroUtils;
import com.maimang.platform.crm.entity.CrmCustomer;
import com.maimang.platform.crm.service.CustomerService;
import com.maimang.platform.enums.BusinessType;
import com.maimang.platform.enums.Status;
import com.maimang.platform.lang.StringUtils;
import com.maimang.platform.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author Rocky
 * @version 1.0.0
 * @classname CustomerController
 * @description <br>客户清单信息操作处理</br>
 * @date 2019-09-23 15:42:23
 * @email jintaozhao@qq.com
 */
@Controller
@RequestMapping("/crm/customer")
@Api(value = "客户清单", description = "客户清单 信息操作处理接口")
public class CustomerController extends BaseController {
	private String prefix = "crm/customer";

	@Autowired
	private CustomerService customerService;

	@Autowired
	private SysUserService userService;

	@Autowired
	private SysDeptService deptService;

	@ApiIgnore
	@RequiresPermissions("crm:customer:view")
	@GetMapping()
	public String customer(ModelMap modelMap, HttpServletResponse response) {
		// 取身份信息
		SysUser user = getSysUser();
		String roleKey = StringUtils.EMPTY;
		for (SysRole role : user.getRoles()) {
			if (StringUtils.isEmpty(roleKey))
				roleKey = role.getRoleKey();
			else
				roleKey.concat("," + role.getRoleKey());
		}
		modelMap.put("user", user);
		modelMap.put("roleKey", roleKey);
		return prefix + "/customer";
	}

	/**
	 * 查询客户清单列表
	 */
	@PassToken
	@ApiOperation(value = "查询列表", notes = "查询客户清单列表信息")
	// @RequiresPermissions("crm:customer:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(CrmCustomer customer) {
		handleParams(customer);
		startPage();
		List<CrmCustomer> list = customerService.selectCustomerList(customer);
		return getDataTable(list);
	}

	private void handleParams(CrmCustomer customer) {
		if (StringUtils.isNotNull(customer.getDeptId())) {
			return;
		}
		SysUser user = ShiroUtils.getSysUser();
		for (SysRole role : user.getRoles()) {
			String roleKey = role.getRoleKey();
			if (roleKey.equalsIgnoreCase(RoleKeyConstant.ADMIN) || roleKey.equalsIgnoreCase(RoleKeyConstant.MASTER_ADMIN) || roleKey.equalsIgnoreCase(RoleKeyConstant.SUB_ADMIN)) {
				customer.setDeptId(1L);
			}
			if (roleKey.equalsIgnoreCase(RoleKeyConstant.EMPLOYEE)) {
				customer.setUserName(user.getUserName());
			}
			if (roleKey.equalsIgnoreCase(RoleKeyConstant.MANAGER)) {
				customer.setDeptId(user.getDeptId());
			}
			if (roleKey.equalsIgnoreCase(RoleKeyConstant.HRBP01) || roleKey.equalsIgnoreCase(RoleKeyConstant.HRBP02)) {
				customer.setDeptId(user.getDeptId());
			}
		}
	}

	@PassToken
	@ApiOperation(value = "查询列表", notes = "查询客户清单列表信息")
	// @RequiresPermissions("crm:customer:list")
	@PostMapping("/all")
	@ResponseBody
	public Result getCustomerMap(CrmCustomer customer) {
		Map<String, List<CrmCustomer>> customerMap = customerService.selectCustomerMap(customer);
		return Result.SUCCESS(customerMap);
	}


	/**
	 * 导出客户清单列表
	 */
	@ApiOperation(value = "导出列表", notes = "导出客户清单列表信息到Excel文件")
	@RequiresPermissions("crm:customer:export")
	@PostMapping("/export")
	@ResponseBody
	public Result export(CrmCustomer customer) {
		handleParams(customer);
		List<CrmCustomer> list = customerService.selectCustomerList(customer);
		ExcelUtil<CrmCustomer> util = new ExcelUtil<CrmCustomer>(CrmCustomer.class);
		return util.exportExcel(list, "客户清单");
	}

	/**
	 * 新增客户清单
	 */
	@ApiIgnore
	@GetMapping("/add")
	public String add() {
		return prefix + "/add";
	}

	/**
	 * 新增保存客户清单
	 */
	@ApiOperation(value = "新增保存", notes = "参数：CrmCustomer")
	@RequiresPermissions("crm:customer:add")
	@Log(title = "客户清单", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public Result addSave(CrmCustomer customer) {
		customer = initCustomer(customer);
		return toResult(customerService.insertCustomer(customer));
	}

	/**
	 * 修改客户清单
	 */
	@ApiIgnore
	@GetMapping("/edit/{customerId}")
	public String edit(@PathVariable("customerId") Integer customerId, ModelMap modelMap) {
		CrmCustomer customer = customerService.selectCustomerById(customerId);
		modelMap.put("customer", customer);
		return prefix + "/edit";
	}

	/**
	 * 修改保存客户清单
	 */
	@ApiOperation(value = "修改保存", notes = "参数：CrmCustomer")
	@RequiresPermissions("crm:customer:edit")
	@Log(title = "客户清单", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public Result editSave(CrmCustomer customer) {
		customer = initCustomer(customer);
		return toResult(customerService.updateCustomer(customer));
	}

	private CrmCustomer initCustomer(CrmCustomer customer) {
		String operName = getSysUser().getLoginName();
		if (StringUtils.isEmpty(customer.getCreateUser()))
			customer.setCreateUser(operName);
		if (StringUtils.isEmpty(customer.getUpdateUser()))
			customer.setUpdateUser(operName);
		if (StringUtils.isNull(customer.getCreateTime()))
			customer.setCreateTime(DateUtils.getNowDate());
		if (StringUtils.isNull(customer.getUpdateTime()))
			customer.setUpdateTime(DateUtils.getNowDate());
		customer.setCreateUser(operName);
		customer.setCreateTime(DateUtils.getNowDate());
		if (customer.getIsNew().equalsIgnoreCase("新客户"))
			customer.setIsCooperated("未合作");
		else if (customer.getIsNew().equalsIgnoreCase("老客户"))
			customer.setIsCooperated("已合作");
		return customer;
	}

	/**
	 * 删除客户清单
	 */
	@ApiOperation(value = "删除对象", notes = "参数：ids，示例： id1,id2,id3，接口会转转为String[]类型")
	@RequiresPermissions("crm:customer:remove")
	@Log(title = "客户清单", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public Result remove(String ids) {
		return toResult(customerService.deleteCustomerByIds(ids));
	}


	@ApiOperation(value = "导入用户", notes = "通过Excel文件导入用户数据")
	@Log(title = "用户管理", businessType = BusinessType.IMPORT)
	@RequiresPermissions("crm:customer:import")
	@PostMapping("/importData")
	@ResponseBody
	public Result importData(MultipartFile file, boolean updateSupport) throws Exception {
		ExcelUtil<CrmCustomer> util = new ExcelUtil<>(CrmCustomer.class);
		List<CrmCustomer> customerList = util.importExcel(file.getInputStream());
		String operName = getSysUser().getLoginName();
		String message = customerService.importCustomer(customerList, updateSupport, operName);
		return Result.SUCCESS(Status.success.code, message);
	}

	@ApiOperation(value = "导入模板", notes = "导入用户信息Excel模板文件")
	@RequiresPermissions("crm:customer:view")
	@GetMapping("/importTemplate")
	@ResponseBody
	public Result importTemplate() {
		ExcelUtil<CrmCustomer> util = new ExcelUtil<>(CrmCustomer.class);
		return util.importTemplateExcel("客户数据");
	}
}